package xulong.com.weiyulinked.config;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;

@Component
public class OnlineUserManage {

    private ConcurrentHashMap<Integer, WebSocketSession> sessionMap = new ConcurrentHashMap<>();

    //用户上线
    public void online(Integer userId, WebSocketSession session) {
        if (sessionMap.get(userId) != null) {
            System.out.println("用户" + userId + "已登录，不能重复登录");
            return;
        }
        sessionMap.put(userId, session);
        System.out.println("用户" + userId + "已上线");
    }

    //用户下线
    public void offline(Integer userId, WebSocketSession session) {
        //如果这俩相等，说明是同一个用户，下线
        if (sessionMap.get(userId) == session) {
            sessionMap.remove(userId);
            System.out.println("用户" + userId + "已下线");
        }
    }

    //根据用户ID获取session
    public WebSocketSession getSession(Integer userId) {
        return sessionMap.get(userId);
    }
}
